Lab8


4531210121_4531214721  น.ส. ฐิติพร วงศ์ไพศาลเจริญ และ น.ส. ธัชนันท์ เตชะสมบูรณากิจ (3/9/2545 (11:53:37))
(SM=2, CM=10, ST=11, KY=0, TR=00:00)

TestScript
Mini-Quiz :  (0.0 คะแนน)

JLab>javac Rational.java
JLab>
JLab>java Selftest
>>JLabIO->recripocate : ok
>>JLabIO->recripocate : ok
>>JLabIO->multiply : ok
>>JLabIO->multiply : ok
>>JLabIO->multiply : ok
>>JLabIO->multiply : ok
>>JLabIO->addMatrix : ok
>>JLabIO->addMatrix : ok

>>JLab:<POINT>8</POINT>
JLab>

ได้ 8 คะแนน
Source Code
// 2110101 : Lab8 (2545)
// dept. of computer engineering
// Chulalongkorn Univ.

import jlab.JLabIO;

public class Rational {
  int numerator;
  int denominator;

  //--------------------------------------------------------
  // an object method returning the recripocal of "this"
  // rational number.
  public Rational recripocate() {

 Rational rec = new Rational(this.denominator,this.numerator);

 return rec;
       

  }
  //--------------------------------------------------------
  // an object method returning the result of "this"
  // rational number multiplied by a.
  public Rational multiply(Rational a) {
  Rational x = new Rational(this.numerator, a.denominator);
  Rational y = new Rational(a.numerator, this.denominator);

  Rational mul = new Rational();
  mul.numerator = x.numerator * y.numerator;
  mul.denominator = x.denominator * y.denominator;
  return mul;  

  }
  //--------------------------------------------------------
  // a class method for multiplying two matrices of rational
  // numbers (matrices a and b).
  public static Rational[][] mulMatrix(Rational[][] a, Rational[][] b) {
  Rational[][] mulM = new Rational[a.length][b[0].length];
  for (int i = 0; i < a.length; i++) {
     for (int j = 0; j < b[0].length; j++) {
       mulM[i][j] = new Rational();
        for (int k = 0; k < b.length; k++) {
          mulM[i][j] = mulM[i][j].add(a[i][k].multiply(b[k][j]));
          }}}
          
     return mulM;

  }
  //--------------------------------------------------------
  // you can use the main method for your own testing (optional).
  public static void main(String[] args) {
    



  }
  //--------------------------------------------------------
  public Rational() {
    this(0, 1);
  }
  public Rational(int n, int d) {
    int g = gcd(n, d);
    n = n / g;
    d = d / g;
    this.numerator = n;
    this.denominator = d;
  }
  public Rational add(Rational a) {
    int g = gcd(this.denominator, a.denominator);
    int d = this.denominator / g * a.denominator;
    int n = this.numerator * d / this.denominator +
            a.numerator * d / a.denominator;
    return new Rational(n, d);
  }
  public String toString() {
    return this.numerator + "/" + this.denominator;
  }
  public static int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}